package com.neu.system.controller;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.neu.system.service.IAcwChatMessagesService;
import com.neu.system.domain.AcwChatMessages;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/deepseek")
public class DeepSeekChatController {

    // 建议后续提取到配置文件
    private static final String API_KEY = "sk-43b60d13ed55405b95be1b7a469567d1";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    @Autowired
    private IAcwChatMessagesService chatMessagesService;

    @PostMapping("/chat")
    public Map<String, Object> chat(@RequestParam("question") String question) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(API_KEY);

        // 构造请求体
        Map<String, Object> body = new HashMap<>();
        body.put("model", "deepseek-chat");
        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "system", "content", "你是一个智能大棚的ai问答名字叫棚博士AI问答主要帮助农户解决农业问题"));
        messages.add(Map.of("role", "user", "content", question));
        body.put("messages", messages);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(API_URL, entity, Map.class);

        // 解析返回内容
        Map<String, Object> result = new HashMap<>();
        if (response.getStatusCode().is2xxSuccessful()) {
            Object choicesObj = response.getBody().get("choices");
            if (choicesObj instanceof List) {
                List choices = (List) choicesObj;
                if (!choices.isEmpty()) {
                    Object messageObj = ((Map) choices.get(0)).get("message");
                    if (messageObj instanceof Map) {
                        Object content = ((Map) messageObj).get("content");
                        result.put("answer", content);
                    }
                }
            }
        } else {
            result.put("error", "调用DeepSeek API失败: " + response.getStatusCode());
        }
        return result;
    }

    @PostMapping("/chat/stream")
    public SseEmitter streamChat(@RequestParam("question") String question, @RequestParam("userId") Long userId) {
        SseEmitter emitter = new SseEmitter(300_000L);
        new Thread(() -> {
            try {
                // 查询历史上下文（最近5条）
                AcwChatMessages filter = new AcwChatMessages();
                filter.setUserId(userId);
                List<AcwChatMessages> history = chatMessagesService.selectAcwChatMessagesList(filter);
                // 只取最近5条，按时间正序
                history = history.stream().sorted((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).toList();
                if (history.size() > 5) history = history.subList(history.size()-5, history.size());

                List<Map<String, String>> messages = new ArrayList<>();
                messages.add(Map.of("role", "system", "content", "你是一个智能大棚的AI问答名字叫棚博士AI问答主要帮助农户解决农业问题"));
                for (AcwChatMessages msg : history) {
                    String role = msg.getRole();
                    if (!"user".equals(role) && !"assistant".equals(role)) continue;
                    messages.add(Map.of("role", role, "content", msg.getContent()));
                }
                messages.add(Map.of("role", "user", "content", question));

                // 构造请求体
                Map<String, Object> body = new HashMap<>();
                body.put("model", "deepseek-chat");
                body.put("messages", messages);
                body.put("stream", true);

                // 发送HTTP流式请求
                URL url = new URL(API_URL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                String json = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(body);
                conn.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));

                InputStream is = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String line;
                StringBuilder fullReply = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) break;
                        // 解析content
                        try {
                            Map map = new com.fasterxml.jackson.databind.ObjectMapper().readValue(data, Map.class);
                            Object choicesObj = map.get("choices");
                            if (choicesObj instanceof List) {
                                List choices = (List) choicesObj;
                                if (!choices.isEmpty()) {
                                    Object deltaObj = ((Map) choices.get(0)).get("delta");
                                    if (deltaObj instanceof Map) {
                                        Object content = ((Map) deltaObj).get("content");
                                        if (content != null) {
                                            String text = content.toString();
                                            fullReply.append(text);
                                            emitter.send(text);
                                        }
                                    }
                                }
                            }
                        } catch (Exception ignore) {}
                    }
                }
                emitter.complete();

                // 保存AI回复到历史
                AcwChatMessages assistantMsg = new AcwChatMessages();
                assistantMsg.setUserId(userId);
                assistantMsg.setRole("assistant");
                assistantMsg.setContent(fullReply.toString());
                chatMessagesService.insertAcwChatMessages(assistantMsg);
            } catch (Exception e) {
                try { emitter.send("[ERROR] " + e.getMessage()); } catch (Exception ignore) {}
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
} 